﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BookstoreDesktopClient
{
    public partial class BookstoreClient : Form
    {
        
        BookWS.BookdbWS booksCollection;
        AccountWS.AccountWS usersCollection;
        BranchWS.BranchWS ordersCollection;
        string role;
        string sessionID;
        int selectedRow = -1;
        string authors_tmp = "";
        double orderSum = 0;

        string HQAccess = "HQ";
        string OnSiteAccess = "on-site";


        public BookstoreClient(string role, string sessionID)
        {
            InitializeComponent();

            this.role = role;
            if (role == "user")
            {
                this.sendButton.Enabled = false;
                this.deleteOrderButton.Enabled = false;
                this.MainControl.TabPages.Remove(usersTabPage);
            }
            this.sessionID = sessionID;

            booksCollection = new BookWS.BookdbWS();
            usersCollection = new AccountWS.AccountWS();
            ordersCollection = new BranchWS.BranchWS();

            try
            {
                getBookData();
                
                var userResult = usersCollection.getallusers(this.sessionID);
                foreach (var j in userResult) userBindingSource.Add(j);

                var orderResult = ordersCollection.getallorders(sessionID);
                foreach (var o in orderResult)
                    orderDataGridView.Rows.Add(o.id, o.client.surname, o.client.name, o.client.email, o.client.phoneNumber.ToString());
                
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        private void logoutLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Hide();
            usersCollection.logoutAsync(sessionID);

            BookstoreClientLogin bcl = new BookstoreClientLogin();
            bcl.Show();
            

        }

        private void BookstoreClient_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void newUserButton_Click(object sender, EventArgs e)
        {
            AddUser addUser = new AddUser(this, usersCollection, sessionID);
            addUser.Show();
        }

        private void newBookButton_Click(object sender, EventArgs e)
        {
            AddBook addBook = new AddBook(this,booksCollection,sessionID);
            addBook.Show();
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            bookDataGridView.RowCount = 0;
            try
            {
                if (searchComboBox.SelectedItem.ToString() == "by Author(s)")
                {
                    var result = booksCollection.searchbyauthorSurname(searchTextBox.Text, sessionID);
                    foreach (var i in result)
                    {
                        authors_tmp = "";
                        foreach (var author in i.authors) authors_tmp += author.name + " " + author.surname + ", ";
                        bookDataGridView.Rows.Add(authors_tmp, i.title, i.publisher.name, i.price, i.amount, i.isbn);
                    }
                }
                else if (searchComboBox.SelectedItem.ToString() == "by Title")
                {
                    var result = booksCollection.searchbyTitle(searchTextBox.Text, sessionID);
                    foreach (var i in result)
                    {
                        authors_tmp = "";
                        foreach (var author in i.authors) authors_tmp += author.name + " " + author.surname + ", ";
                        bookDataGridView.Rows.Add(authors_tmp, i.title, i.publisher.name, i.price, i.amount, i.isbn);
                    }
                }
                else if (searchComboBox.SelectedItem.ToString() == "by Publisher")
                {
                    var result = booksCollection.searchbypublisher(searchTextBox.Text, sessionID);
                    foreach (var i in result)
                    {
                        authors_tmp = "";
                        foreach (var author in i.authors) authors_tmp += author.name + " " + author.surname + ", ";
                        bookDataGridView.Rows.Add(authors_tmp, i.title, i.publisher.name, i.price, i.amount, i.isbn);
                    }
                }
                else if (searchComboBox.SelectedItem.ToString() == "by ISBN")
                {
                    var result = booksCollection.getbook(searchTextBox.Text, sessionID);
                    authors_tmp = "";
                    foreach (var author in result.authors) authors_tmp += author.name + " " + author.surname + ", ";
                    bookDataGridView.Rows.Add(authors_tmp, result.title, result.publisher.name, result.price, result.amount, result.isbn);
                }
            }
            catch (Exception exc)
            {
                exc.ToString();
                MessageBox.Show("No results found!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void showAllBooksButton_Click(object sender, EventArgs e)
        {
            bookDataGridView.RowCount = 0;
            getBookData();

        }

        private void removeUserButton_Click(object sender, EventArgs e)
        {
            this.selectedRow = userDataGridView.CurrentRow.Index;
            if (MessageBox.Show("Are you sure you would like to delete the user?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                usersCollection.removeuserAsync(userDataGridView.Rows[selectedRow].Cells[0].Value.ToString(), sessionID);
                usersCollection.removeuserCompleted += new AccountWS.removeuserCompletedEventHandler(usersCollection_removeuserCompleted);
            }
        }

        private void usersCollection_removeuserCompleted(object sender, AccountWS.removeuserCompletedEventArgs e)
        {
            if (e.@return) this.infoUserLabel.Text = "Given user account has been removed!";
            else this.infoUserLabel.Text = e.ToString();

            this.refreshListOfUsers();
        }

        public void refreshListOfUsers()
        {
            userBindingSource.Clear();

            var userResult = usersCollection.getallusers(sessionID);
            foreach (var j in userResult) userBindingSource.Add(j); 
        }

        private void makePurchaseButton_Click(object sender, EventArgs e)
        {
            List<BranchWS.orderItem> orderItemList = new List<BranchWS.orderItem>();
            
            foreach (DataGridViewRow row in bookDataGridView.Rows)
            {
                if (Convert.ToBoolean(row.Cells[orderColumn.Name].Value) == true && row.Cells[accessibility.Name].Value.Equals(OnSiteAccess))
                {
                    try
                    {
                        orderItemList.Add(
                        newOrderItem(booksCollection.getbook(row.Cells[isbnColumn.Name].Value.ToString(), sessionID),
                        Convert.ToInt32(row.Cells[quantityColumn.Name].Value.ToString())
                        ));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("An error occured:\n" + ex.ToString());
                    }
                }

                if (Convert.ToBoolean(row.Cells[orderColumn.Name].Value) == true && row.Cells[accessibility.Name].Value.Equals(HQAccess))
                {
                    try
                    {
                        orderItemList.Add(
                            newOrderItemHQ(row.Cells[isbnColumn.Name].Value.ToString(), Convert.ToInt32(row.Cells[quantityColumn.Name].Value.ToString())
                            ));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("An error occured:\n" + ex.ToString());
                    }
                }
            }

            if (orderSum > 0.0)
            {
                AddOrder addOrder = new AddOrder(this, orderSum, orderItemList, sessionID, ordersCollection);
                addOrder.Show();
            }
            else
            {
                MessageBox.Show("Nothing has been marked to be ordered!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private BranchWS.orderItem newOrderItemHQ(String book_isbn, int quantity)
        {
            var bookResultHQ = booksCollection.getallavailablebooks(this.sessionID);
            BranchWS.orderItem branch_order = new BranchWS.orderItem();
            BranchWS.book branch_book = new BranchWS.book();
            BranchWS.author[] branch_authors; //= new BranchWS.author[book_book.authors.Length];
            BranchWS.author a;
            BranchWS.publisher branch_publisher = new BranchWS.publisher();

            foreach (var k in bookResultHQ)
            {
                if (k.isbn == book_isbn)
                {
                    branch_book.amount = k.amount;
                    branch_authors = new BranchWS.author[k.authors.Length];
                    for (int i = 0; i < k.authors.Length; i++)
                    {
                        a = new BranchWS.author();
                        a.id = k.authors[i].id;
                        a.name = k.authors[i].name;
                        a.surname = k.authors[i].surname;
                        branch_authors[i] = a;
                    }
                    branch_book.authors = branch_authors;
                    branch_book.isbn = k.isbn;
                    branch_book.price = k.price;

                    branch_publisher.id = k.publisher.id;
                    branch_publisher.name = k.publisher.name;
                    branch_book.publisher = branch_publisher;
                    branch_book.title = k.title;

                    branch_order.book = branch_book;
                    branch_order.quantity = quantity;
                    break;
                }
            }
            return branch_order;
        }

        private BranchWS.orderItem newOrderItem(BookWS.book book_book, int quantity)
        {
            BranchWS.orderItem branch_order = new BranchWS.orderItem();
            BranchWS.book branch_book = new BranchWS.book();
            BranchWS.author[] branch_authors = new BranchWS.author[book_book.authors.Length];
            BranchWS.author a;
            BranchWS.publisher branch_publisher = new BranchWS.publisher();

            branch_book.amount = book_book.amount;
            for (int i = 0; i < book_book.authors.Length; i++)
            {
                a = new BranchWS.author();
                a.id = book_book.authors[i].id;
                a.name = book_book.authors[i].name;
                a.surname = book_book.authors[i].surname;
                branch_authors[i] = a;
            }
            branch_book.authors = branch_authors;
            branch_book.isbn = book_book.isbn;
            branch_book.price = book_book.price;

            branch_publisher.id = book_book.publisher.id;
            branch_publisher.name = book_book.publisher.name;
            branch_book.publisher = branch_publisher;
            branch_book.title = book_book.title;

            branch_order.book = branch_book;
            branch_order.quantity = quantity;

            return branch_order;

        }

        private void editBookButton_Click(object sender, EventArgs e)
        {
            if (bookDataGridView.CurrentRow.Cells[accessibility.Name].Value.Equals(OnSiteAccess))
            {
                string s = bookDataGridView.CurrentRow.Cells[isbnColumn.Name].Value.ToString();
                BookWS.book selectedBook = booksCollection.getbook(s, sessionID);

                EditBookForm editBookForm = new EditBookForm(this, booksCollection, sessionID, selectedBook);
                editBookForm.Show();
            }
            else
            {
                MessageBox.Show("You cannot edit books from Headquarter", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
        }

        private void deleteBookButton_Click(object sender, EventArgs e)
        {
            if (bookDataGridView.CurrentRow.Cells[accessibility.Name].Value.Equals(OnSiteAccess))
            {
                this.selectedRow = bookDataGridView.CurrentRow.Index;
                if (MessageBox.Show("Are you sure you would like to delete this book?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    booksCollection.removeBookAsync(bookDataGridView.Rows[selectedRow].Cells[isbnColumn.Name].Value.ToString(), sessionID);
                    booksCollection.removeBookCompleted += new BookWS.removeBookCompletedEventHandler(booksCollection_removebookCompleted);
                }
            }
            else
            {
                MessageBox.Show("You cannot delete books from Headquarter", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            
        }

        private void booksCollection_removebookCompleted(object sender, BookWS.removeBookCompletedEventArgs e)
        {
            if (e.@return) this.sumLabel.Text = "The book has been removed!";
            else this.sumLabel.Text = e.ToString();

            this.showAllBooksButton_Click(sender, e);
        }
              
        private void bookDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int column = e.ColumnIndex;
            int row = e.RowIndex;

            // aby checkbox'y działały:)
            if (column == 7)
            {
                if (Convert.ToBoolean(bookDataGridView.Rows[row].Cells[orderColumn.Name].Value))
                {
                    bookDataGridView.Rows[row].Cells[orderColumn.Name].Value = false;
                    orderSum -= Convert.ToDouble(bookDataGridView.Rows[row].Cells[priceColumn.Name].Value) * Convert.ToInt32(bookDataGridView.Rows[row].Cells[quantityColumn.Name].Value);
                    bookDataGridView.Rows[row].Cells[quantityColumn.Name].ReadOnly = true;
                    bookDataGridView.Rows[row].Cells[quantityColumn.Name].Value = "";
                }
                else
                {
                    bookDataGridView.Rows[row].Cells[orderColumn.Name].Value = true;
                    bookDataGridView.Rows[row].Cells[quantityColumn.Name].ReadOnly = false;
                    bookDataGridView.Rows[row].Cells[quantityColumn.Name].Value = 1;
                    orderSum += Convert.ToDouble(bookDataGridView.Rows[row].Cells[priceColumn.Name].Value) * Convert.ToInt32(bookDataGridView.Rows[row].Cells[quantityColumn.Name].Value);           
                }
            }
           
            this.sumLabel.Text = "Order Sum: " + orderSum + " PLN.";   
            
        }

        private void bookDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            
            orderSum = 0.0;
            //try
            //{
                foreach (DataGridViewRow row in bookDataGridView.Rows)
                {
                    if (Convert.ToBoolean(row.Cells[orderColumn.Name].Value) == true) orderSum += Convert.ToDouble(row.Cells[priceColumn.Name].Value) * Convert.ToInt32(row.Cells[quantityColumn.Name].Value);
                }
                this.sumLabel.Text = "Order Sum: " + orderSum + " PLN.";
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("An error occured:\n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void showOrderButton_Click(object sender, EventArgs e)
        {
            try
            {
                int orderid = Convert.ToInt32(orderIdTextBox.Text);
                var r = ordersCollection.getorder(orderid, sessionID);            
                this.orderDataGridView.RowCount = 0;
                this.orderDataGridView.Rows.Add(r.id, r.client.surname, r.client.name, r.client.email, r.client.phoneNumber);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void deleteOrderButton_Click(object sender, EventArgs e)
        {
            try
            {
                ordersCollection.removeorderAsync(Convert.ToInt32(orderIdTextBox.Text), sessionID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            ordersCollection.removeorderCompleted += new BranchWS.removeorderCompletedEventHandler(ordersCollection_removeorderCompleted);
        }

        void ordersCollection_removeorderCompleted(object sender, BranchWS.removeorderCompletedEventArgs e)
        {
            if (e.@return) this.infoOrderLabel.Text = "The order has been removed.";
            else this.sumLabel.Text = e.ToString();

            this.showAllOrdersButton_Click(sender, e);
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            try
            {
                ordersCollection.processordersAsync(sessionID);
                ordersCollection.processordersCompleted += new BranchWS.processordersCompletedEventHandler(ordersCollection_processordersCompleted);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured:\n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void ordersCollection_processordersCompleted(object sender, BranchWS.processordersCompletedEventArgs e)
        {
            if (e.@return) this.infoOrderLabel.Text = "The orders have been processed.";
            else this.infoOrderLabel.Text = e.ToString();

            showAllOrdersButton_Click(sender, e);
        }

        public void showAllOrdersButton_Click(object sender, EventArgs e)
        {
            orderDataGridView.RowCount = 0;
            var orderResult = ordersCollection.getallorders(sessionID);
            foreach (var o in orderResult)
                orderDataGridView.Rows.Add(o.id, o.client.surname, o.client.name, o.client.email, o.client.phoneNumber);

            this.infoOrderLabel.Text = "";
        }

        private void getBookData()
        {
            var bookResult = booksCollection.getallbooks(this.sessionID);
            var bookResultHQ = booksCollection.getallavailablebooks(this.sessionID);

            foreach (var i in bookResult)
            {
                authors_tmp = "";
                for (int j = 0; j < i.authors.Length; j++) authors_tmp += i.authors[j].name + " " + i.authors[j].surname + ", ";
                bookDataGridView.Rows.Add(authors_tmp, i.title, i.publisher.name, i.price, i.amount, i.isbn, "on-site");
            }

            foreach (var k in bookResultHQ)
            {
                authors_tmp = "";
                for (int m = 0; m < k.authors.Length; m++) authors_tmp += k.authors[m].name + " " + k.authors[m].surname + ", ";
                bookDataGridView.Rows.Add(authors_tmp, k.title, k.publisher.name, k.price, k.amount, k.isbn, "HQ");
            }
        }

    }
}
